# 取最近的一个
from datetime import datetime

PAGE_SIZE = 1
BASE_URL = 'https://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name={name}&issueCount=&issueStart=&issueEnd=&dayStart=&dayEnd=&pageNo=1&pageSize={page_size}&week=&systemType=PC'

def get_date_week():
    # 定义星期对应列表
    weekday_map = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]

    today = datetime.today()
    # 使用 weekday() 结果作为索引获取中文星期
    weekday_str = weekday_map[today.weekday()]
    return {
        "date":today.strftime("%Y年%m月%d日") + " " + weekday_str
    }

def get_url(page_size, name):
    """生成请求URL"""
    return BASE_URL.format(page_size=page_size, name=name)


def get_result_json(name):
    """获取并解析JSON数据"""
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.5',
            'Referer': 'https://www.baidu.com/'  # 根据实际网站填写
        }
        url = get_url(PAGE_SIZE, name)  # 修复参数传递错误
        response = requests.get(url, timeout=10, headers=headers)
        response.raise_for_status()  # 抛出HTTP错误状态码

        data = response.json()
        # 检查返回结果是否存在
        if not data or 'result' not in data or not data['result']:
            raise ValueError(f"未获取到{name}的有效数据")

        # 返回第一个结果（最近的一期）
        return data['result'][0]

    except requests.exceptions.RequestException as e:
        raise ConnectionError(f"网络请求错误: {str(e)}")
    except (KeyError, IndexError) as e:
        raise ValueError(f"数据解析错误: {str(e)}")


def get_ssq_result():
    """获取双色球结果"""
    try:
        ssq_info = get_result_json('ssq')
        return {
            'ssq_code': ssq_info.get('code'),
            'ssq_red_info': ssq_info.get('red', '').split(','),
            'ssq_blue': ssq_info.get('blue')
        }
    except Exception as e:
        raise ValueError(f"获取双色球数据失败: {str(e)}")


def get_kl8_result():
    """获取快乐8结果"""
    try:
        kl8_info = get_result_json('kl8')
        return {
            'kl8_code': kl8_info.get('code'),
            'kl8_red_info': kl8_info.get('red', '').split(',')
        }
    except Exception as e:
        raise ValueError(f"获取快乐8数据失败: {str(e)}")

def get_3d_result():
    """获取3d结果"""
    try:
        d3_info = get_result_json('3d')
        return {
            'd3_code': d3_info.get('code'),
            'd3_red_info': d3_info.get('red', '').split(',')
        }
    except Exception as e:
        raise ValueError(f"获取3d数据失败: {str(e)}")

def get_qlc_result():
    """获取qlc结果"""
    try:
        d3_info = get_result_json('qlc')
        return {
            'qlc_code': d3_info.get('code'),
            'qlc_blue': d3_info.get('blue'),
            'qlc_red_info': d3_info.get('red', '').split(',')
        }
    except Exception as e:
        raise ValueError(f"获取七乐彩数据失败: {str(e)}")


def get_result():
    """整合所有结果"""
    # 获取当前日期
    today = datetime.today()
    return {
        **get_date_week(),
        **get_ssq_result(),
        **get_kl8_result(),
        **get_3d_result(),
        **get_qlc_result()
    }